import React, { Component } from 'react';
import { View, FlatList, Text, ActivityIndicator, StyleSheet } from 'react-native';
import { queryToday, comingMovies } from '../common/Service';
import GankTodayCell from "../widgets/GankTodayCell";

export default class GankTodayScreen extends Component {

  static navigationOptions = {
    headerTitle: '今日干货'
  };

  constructor(props) {
    super(props);
    //不使用Redux来改变状态比较容易懂
    this.state = {
      dataList: [],  // 列表的数据源
      loaded: false,  // 用来控制loading视图的显示，当数据加载完成，loading视图不再显示
    };
  }

  componentDidMount() {
    /// 根据routeName来判断当前是哪个界面，react-navigation中可以通过navigation.state.routeName来获取
    let routeName = this.props.navigation.state.routeName;
    if (routeName === 'Init') {
      this.loadToday();
    }
  }
  onViewableItemsChanged = ({ viewableItems, changed }) => {
    console.log("Visible items are", viewableItems);//缓存item的ref引用就可以在这里控制item,参考https://my.oschina.net/sfshine/blog/3069509
    console.log("Changed in this iteration", changed);
  }

  render() {
    if (!this.state.loaded) {
      return (
        <View style={styles.loadingView}>
          <ActivityIndicator animating={true} size="small" />
          <Text style={{ color: '#666666', paddingLeft: 10 }}>努力加载中</Text>
        </View>
      )
    }
    return (
      <FlatList
        onViewableItemsChanged={this.onViewableItemsChanged}
        viewabilityConfig={{
          itemVisiblePercentThreshold: 50
        }}
        data={this.state.dataList}
        renderItem={this._renderItem}
        keyExtractor={(data) => data._id}
      />
    )
  }

  _renderItem = (data) => {
    let item = data.item;
    return (
      data.index % 2 == 0 ? <GankTodayCell item={item} onPress={() => {
        console.log('点击了item----' + item.desc);
      }} /> : <Text>{item.desc}</Text>//多个Item展示
    )
  };
  loadToday() {
    let that = this;
    fetch(queryToday()).then((response) => response.json()).then((json) => {
      console.log(json);
      that.setState({
        dataList: json.results.Android,
        loaded: true
      })
    }).catch((e) => {
      console.log("加载失败");
      that.setState({
        loaded: true
      })
    }).done();
  }
}
const styles = StyleSheet.create({
  loadingView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10
  }
});
